Mybatis框架(13) —— 实现多表查询的延迟加载操作(基于注解)

简介

MyBatis中多表之间的关系

  • 本次案例主要以最为简单的用户(User)、账户(Account)、角色(Role)的模型来分析Mybatis多表关系。
    • 用户为User 表,账户为Account表。
      • 一对多关系
        • 一个用户(User)可以开设多个账户(Account)
          • 从查询 用户信息(User) 出发,关联查询 账户信息(Account)属于一对多查询
      • 一对一关系(多对一)
        • 多个账户(Account)可以对应一个用户(User)
        • 单个账户(Account)只能属于一个用户(User)
          • 从查询 账户信息(Account) 出发,关联查询 用户信息(User)属于一对一查询
      • 多对多关系
        • 一个用户(User)可以拥有多个角色(Role)
        • 一个角色(Role)可以赋予多个用户(User)
          • 多对多关系其实我们看成是双向的一对多关系。

目录结构

  • src
    • main
      • java
        • cn.water.dao
          • UserDao.java(一对多 持久层接口)
          • AccountDao.java(一对一 持久层接口)
        • cn.water.domain
          • User.java(一对多 实体类)
          • Account.java(一对一 实体类)
      • resources
        • cn.water.dao
          • User.xml(一对多 映射配置文件)
          • Account.xml(一对一 映射配置文件)
        • SqlMapConfig.xml(MyBatis主配置文件)
        • jdbcConfig.properties(数据库连接信息文件)
    • test
      • java.cn.water
        • MybatisTest.java(测试类)

MyBatis主配置文件

jdbcConfig.properties

1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

SqlMapConfig.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">


<!-- mybatis的主配置文件 -->
<configuration>

<!-- 外部配置 -->
<properties resource="jdbcConfig.properties"></properties>

<!-- 配置参数 -->
<settings>
<!-- 开启 延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>

<!-- 指定包:实体类-->
<typeAliases>
<package name="cn.water.domain"/>
</typeAliases>

<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>

<!-- 指定包:持久层接口 -->
<mappers>
<package name="cn.water.dao"/>
</mappers>

</configuration>

实体类

Account.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cn.water.domain;

import java.io.Serializable;

/**
* @author Water
* @date 2019/10/13 - 15:10
* @description
*/
public class Account implements Serializable {

private Integer id;
private Integer uid;
private Double money;
private User user;

@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
", user=" + user +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getUid() {
return uid;
}

public void setUid(Integer uid) {
this.uid = uid;
}

public Double getMoney() {
return money;
}

public void setMoney(Double money) {
this.money = money;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}
}

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package cn.water.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
* @author Water
* @date 2019/10/13 - 15:10
* @description
*/
public class User implements Serializable {

private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
private List<Account> accounts;

@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", accounts=" + accounts +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public List<Account> getAccounts() {
return accounts;
}

public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}

持久层接口

AccountDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package cn.water.dao;

import cn.water.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* @author Water
* @date 2019/10/13 - 15:11
* @description 一对一查询 延迟查询
*/
public interface AccountDao {

/* 一对一查询:查询所有账户信息和对应的用户信息 */
@Select("SELECT * FROM account")
@Results(id = "accountMap",
value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
/* 传递值:uid,变量名:user */
@Result(column = "uid",
property = "user",
one = @One(select = "cn.water.dao.UserDao.findById",
fetchType = FetchType.LAZY
)
)

})
List<Account> findAll();


/* 一对多查询:根据id,查询账户信息 */
@Select("SELECT * FROM account WHERE uid = #{id}")
Account findByUid(Integer id);

}

UserDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package cn.water.dao;

import cn.water.domain.User;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* @author Water
* @date 2019/10/13 - 15:11
* @description 一对多查询 延迟查询
*/
public interface UserDao {

/* 一对一查询:按照id,查询用户信息 */
@Select("SELECT * FROM user WHERE id = #{id}")
User findById();

/* 一对多查询:查询所有的用户信息和对应的账户信息 */
@Select("SELECT * FROM user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "birthday",property = "birthday"),
@Result(column = "sex",property = "sex"),
@Result(column = "address",property = "address"),
/* 传递值:uid,变量名:accounts */
@Result(column = "id",
property = "accounts",
many = @Many(select = "cn.water.dao.AccountDao.findByUid",
fetchType = FetchType.LAZY
)
)
})
List<User> findAll();

}

测试类

MyBatisTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cn.water;

import cn.water.dao.AccountDao;
import cn.water.dao.UserDao;
import cn.water.domain.Account;
import cn.water.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
* @author Water
* @date 2019/10/13 - 10:48
* @description
*/
public class UserTest {

private InputStream inputStream;
private SqlSessionFactory factory;
private SqlSession session;


@Before
public void init() throws IOException {
inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(inputStream);
session = factory.openSession(true);
}

@After
public void destroy () throws IOException {
session.close();
inputStream.close();
}


/** 一对一查询 */
@Test
public void test01(){
AccountDao dao = session.getMapper(AccountDao.class);
for (Account account : dao.findAll()) {
System.out.println(account);
}
}


/** 一对多查询 */
@Test
public void test02(){
UserDao dao = session.getMapper(UserDao.class);
for (User user : dao.findAll()) {
System.out.println(user);
}
}



}

一对一查询(延迟)

  • @One注解代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
  • 注解
    • @One:实现一对一结果集封装
      • select:指定用来多表查询的sqlmapper
      • fetchType:覆盖全局的配置参数(延迟加载:lazyLoadingEnabled)

账户类 持久层接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Select("SELECT * FROM account")
@Results(id = "accountMap",
value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
/* 传递值:uid,变量名:user */
@Result(column = "uid",
property = "user",
one = @One(select = "cn.water.dao.UserDao.findById",
fetchType = FetchType.LAZY
)
)

})
List<Account> findAll();

用户类 持久层接口

1
2
@Select("SELECT * FROM user WHERE id = #{id}")
User findById();

测试类

1
2
3
4
5
6
7
@Test
public void test01(){
AccountDao dao = session.getMapper(AccountDao.class);
for (Account account : dao.findAll()) {
System.out.println(account);
}
}

运行结果

![](13.注解 多表查询 延迟加载\注解 一对一查询 延迟查询.png)

一对多查询(延迟)

  • @Many注解代替了<Collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
  • 注解
    • @Many:实现一对多结果集封装
      • select:指定用来多表查询的sqlmapper
      • fetchType:覆盖全局的配置参数(延迟加载:lazyLoadingEnabled)

用户类 持久层接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Select("SELECT * FROM user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(column = "birthday",property = "birthday"),
@Result(column = "sex",property = "sex"),
@Result(column = "address",property = "address"),
/* 传递值:uid,变量名:accounts */
@Result(column = "id",
property = "accounts",
many = @Many(select = "cn.water.dao.AccountDao.findByUid",
fetchType = FetchType.LAZY
)
)
})
List<User> findAll();

账户类 持久层接口

1
2
@Select("SELECT * FROM account WHERE uid = #{id}")
Account findByUid(Integer id);

测试类

1
2
3
4
5
6
7
@Test
public void test02(){
UserDao dao = session.getMapper(UserDao.class);
for (User user : dao.findAll()) {
System.out.println(user);
}
}

运行结果

![](13.注解 多表查询 延迟加载\注解 一对多查询 延迟查询.png)

-------------本文结束-------------
Donate comment here